package com.ebupt.migu.music.global.schedule;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ebupt.migu.globalpopup.entity.ActivityInfo;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.global.mapper.ActivityInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 定时任务
 *
 * @author wangzhu
 * @since 2021-11-26
 */
@EnableScheduling
@Component
@Slf4j
public class GlobalTask {

    @Resource
    ActivityInfoMapper activityInfoMapper;

    /**
     * 每分钟
     */
    @Async
    @Scheduled(cron = "${cron.chameleon_status_update}")
    public void everyMinuteControl() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        // 当前时间
        String now = simpleDateFormat.format(date);
        log.info("查询活动，修改活动状态，当前时间：{}", now);
        UpdateWrapper<ActivityInfo> supdate = new UpdateWrapper<>();
        supdate
                .lambda()
                .eq(true, ActivityInfo::getActivityStatus, 3)
                .apply("activity_start < '" + now + "'")
                .set(true, ActivityInfo::getActivityStatus, 4);
        try {
            int i = activityInfoMapper.update(new ActivityInfo(), supdate);
            log.info("已将{}个活动的状态改为进行中！", i);
        } catch (Exception e) {
            log.error("活动的状态修改失败",e);
            throw new MyException(StatusEnum.ERROR, "修改失败");
        }
        UpdateWrapper<ActivityInfo> nupdate = new UpdateWrapper<>();
        nupdate
                .lambda()
                .in(true, ActivityInfo::getActivityStatus, 4, 5)
                .apply("activity_end < '" + now + "'")
                .set(true, ActivityInfo::getActivityStatus, 6);
        try {
            int j = activityInfoMapper.update(new ActivityInfo(), nupdate);
            log.info("已将{}个活动的状态改为已完成！", j);
        } catch (Exception e) {
            log.error("活动的状态修改失败",e);
            throw new MyException(StatusEnum.ERROR, "修改失败");
        }
    }
}
